package com.powergisol.gis.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 *
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer{

    /**
     * Cors（跨域请求）配置
     * @param corsRegistry
     */
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry){


        corsRegistry.addMapping("/**")   //   /**代表所有路径
                    .allowedOrigins("*")    //允许访问的客户端域名，若为*，则表示从任意域都能访问，即不受任何限制
                    .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")//允许访问的方法名
                    .allowCredentials(true)//表示是否允许发送cookie，当设置为true时，客户端的ajax请求，也需要将withCredentials设置为true
                    .maxAge(3600);//表示在3600秒内不需要再发送检验请求
    }
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();
        //生成json时，将所有Long转换成String

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(0, jackson2HttpMessageConverter);
    }
}
